
/*
 *  
 *
 *  Copyright (C) Microsoft Corporation.  All rights reserved
 *
 *  
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections.Specialized;
using System.Reflection;
using Microsoft.Crm.DataBindining;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

namespace CRMScenarios
{
    /// <summary>
    /// Insert field pane.
    /// </summary>
    public partial class InsertFlds : CRMScenarios.BaseUserControl
    {
        // once you go to pick list and come back, the selected index is lost. so we need this.
        int[] selectedIndicesOfRelatedRecords = null;
        bool selectAllChangedProgrammatically = false;
        bool attribSelectionChangedProg = false;

        /// <summary>
        /// Contructor  - Initializes many of the controls and event handlers.
        /// </summary>
        public InsertFlds()
        {
            InitializeComponent();
            this.SizeChanged += new EventHandler(InsertFlds_SizeChanged);
            this.SetStyle(ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor, true);
            BackColor = Color.FromArgb(1, 0, 0, 0);
            this.UpdateStyles(); 
            FlagErrorOrWarning(global::CRMScenarios.Resources.Initializing, InfoOptions.Busy);

            cmBoxRelated.SelectedIndexChanged += new System.EventHandler(cmBoxRelated_SelectedIndexChanged);
            textBoxLookForText.TextChanged += new System.EventHandler(tBoxSearchFor_TextChanged);
            buttonGoSearch.Click += new System.EventHandler(buttonGoSearch_Click);

            splitButton1.ShowSplit = true;
            splitButton1.ContextMenuStrip = new ContextMenuStrip();
            splitButton1.ContextMenuStrip.MouseCaptureChanged += new EventHandler(ContextMenuStrip1_MouseCaptureChanged);
            splitButton1.ContextMenuStrip.Items.Add(global::CRMScenarios.Resources.InsertRelatedRecordMenu);
            splitButton1.ContextMenuStrip.Items[0].Click += new EventHandler(twoToolStripMenuItem_Click);
            splitButton1.ContextMenuStrip.Items.Add(global::CRMScenarios.Resources.InsertRelatedRecordWithAdditionalColumnsMenu);
            splitButton1.ContextMenuStrip.Items[1].Click += new EventHandler(threeToolStripMenuItem_Click);
            splitButton1.Click += new EventHandler(twoToolStripMenuItem_Click);


            SplitBtnInsertDetail.ShowSplit = true;
            SplitBtnInsertDetail.ContextMenuStrip = new ContextMenuStrip();
            SplitBtnInsertDetail.ContextMenuStrip.MouseCaptureChanged += new EventHandler(ContextMenuStrip_MouseCaptureChanged);
            SplitBtnInsertDetail.ContextMenuStrip.Items.Add(global::CRMScenarios.Resources.InsertRecordMenu);
            SplitBtnInsertDetail.ContextMenuStrip.Items[0].Click += new EventHandler(SplitBtnInsertDetail_InsertRec_click);
            SplitBtnInsertDetail.ContextMenuStrip.Items.Add(string.Empty);
            SplitBtnInsertDetail.ContextMenuStrip.Items[1].Click += new EventHandler(SplitBtnInsertDetail_InsertRec_AsTable_click);
            SplitBtnInsertDetail.Click += new EventHandler(SplitBtnInsertDetail_InsertRec_click);

            lnklblOtherTask.MouseHover += new EventHandler(UnderLineTheLabel);
            lnklblWarning.MouseHover += new EventHandler(UnderLineTheLabel);
            lnkLblTips.MouseHover += new EventHandler(UnderLineTheLabel);

            lnklblOtherTask.MouseLeave += new EventHandler(UndoUnderLineTheLabel);
            lnklblWarning.MouseLeave += new EventHandler(UndoUnderLineTheLabel);
            lnkLblTips.MouseLeave += new EventHandler(UndoUnderLineTheLabel);

            listViewOfRelatedRecordDetails.CellDoubleClick += new DataGridViewCellEventHandler(listViewOfRelatedRecordDetails_DoubleClick);
            listViewOfRelatedRecordDetails.SelectionChanged += new EventHandler(listViewRelated_SelectedIndexChanged);
            listViewOfRecordDetails.SelectionChanged += new EventHandler(listViewDetails_SelectedIndexChanged);

            listViewOfRelatedRecordDetails.CellMouseEnter += new DataGridViewCellEventHandler(dataGridView_CellMouseEnter);
            listViewOfRelatedRecordDetails.LostFocus += new EventHandler(listViewOfRelatedRecordDetailsRemoveContextMenu);
            listViewOfRelatedRecordDetails.MouseDown += new MouseEventHandler(listViewOfRelatedRecordDetailsRemoveContextMenu);
            listViewOfRelatedRecordDetails.DataError += new DataGridViewDataErrorEventHandler(RelatedGridDataError);


            textBoxLookForText.KeyDown += new KeyEventHandler(textBoxLookForText_KeyDown);
            this.panelOtherTask.MouseDown += new MouseEventHandler(panelOtherTask_MouseDown);
            this.firstPagePic.Click += new System.EventHandler(this.firstPagePic_Click);
            this.previousPagePic.Click += new System.EventHandler(this.previousPagePic_Click);
            this.nextPagePic.Click += new System.EventHandler(this.nextPagePic_Click);
            this.PicBtnBack.Click += new System.EventHandler(this.PicBtnBack_Click);
            this.PicBtnForward.Click += new System.EventHandler(this.PicBtnForward_Click);

            CBoxSelectAllRelRec.CheckedChanged += new EventHandler(CBoxSelectAllRelRec_CheckedChanged);
            DisableAllControls();
            this.Refresh();
        }

        void listViewOfRelatedRecordDetailsRemoveContextMenu(object sender, EventArgs e)
        {
            // have a bug of not disappearing. when clicked on a scroll bar.
            if(listViewOfRelatedRecordDetails.Enabled == false)
            {
                return ;
            }

            foreach (DataGridViewRow row in listViewOfRelatedRecordDetails.Rows)
            {
                if (row.ContextMenuStrip != null)
                {
                    row.ContextMenuStrip.Close();
                    row.ContextMenuStrip.Hide();
                }
            }
        }

        /// <summary>
        /// This contains the resizing logic for the control. 
        /// On horizontal resizing of the cotrol, the internal control change the size accordingly.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void InsertFlds_SizeChanged(object sender, EventArgs e)
        {
            if (Width < (lblHeading.Width + (2 * xPadding) + 8))
            {
                return;
            }

            // the first section is of those controls whose size wont change. (actually location too wont change).
            lblHeading.Location = new Point(xPadding, lblHeading.Location.Y);
            labelLookFor.Location = new Point(xPadding, labelLookFor.Location.Y);
            labelLookIn.Location = new Point(xPadding, labelLookIn.Location.Y);
            lblSelectHeading.Location = new Point(xPadding, lblSelectHeading.Location.Y);
            lblSelectRelHeading.Location = new Point(xPadding, lblSelectRelHeading.Location.Y);
            lblRelated.Location = new Point(xPadding, lblRelated.Location.Y);

            lblNoRecordFound.Location = new Point(((this.Width - lblNoRecordFound.Width) / 2), lblNoRecordFound.Location.Y);

            panelOtherTask.Size = new Size(Width - 2 * xPadding, panelOtherTask.Size.Height);
            panelOtherTask.Location = new Point(xPadding, panelOtherTask.Location.Y);
            lnklblWarning.Size = new Size(panelOtherTask.Width - picWarning.Width - 2 * xPadding, lnklblWarning.Height);
            lnklblWarning.Location = new Point(2 * xPadding + picWarning.Width, lnklblWarning.Location.Y);
            lnkLblTips.Location = new Point(2 * xPadding + picHelp.Width, lnkLblTips.Location.Y);

            cBoxSelAll.Location = new Point(xPadding, cBoxSelAll.Location.Y);
            lblCBoxSelectAll.Location = new Point(cBoxSelAll.Location.X + cBoxSelAll.Width, lblCBoxSelectAll.Location.Y);

            comboBoxEntityTypeLookFor.Size = new Size(Width - labelLookIn.Width - 3 * xPadding, comboBoxEntityTypeLookFor.Size.Height);
            comboBoxEntityTypeLookFor.Location = new Point(xPadding + labelLookIn.Width + xPadding, comboBoxEntityTypeLookFor.Location.Y);

            buttonGoSearch.Location = new Point(Width - xPadding - buttonGoSearch.Width, buttonGoSearch.Location.Y);

            textBoxLookForText.Size = new Size(Width - buttonGoSearch.Width - labelLookFor.Width - 4 * xPadding, textBoxLookForText.Size.Height);
            textBoxLookForText.Location = new Point(2 * xPadding + labelLookFor.Width, textBoxLookForText.Location.Y);

            cmBoxRelated.Size = new Size(Width - 3 * xPadding - lblRelated.Width, cmBoxRelated.Size.Height);
            cmBoxRelated.Location = new Point(2 * xPadding + lblRelated.Width, cmBoxRelated.Location.Y);

            int lstViewWdth = Width - 2 * xPadding;
            listViewOfRecordDetails.Size = new Size(lstViewWdth, listViewOfRecordDetails.Height);
            listViewOfRecordDetails.Location = new Point(xPadding, listViewOfRecordDetails.Location.Y);
            listViewOfRecordDetails.Columns[0].AutoSizeMode =  (((lstViewWdth / 2) > listViewOfRecordDetails.Columns[0].Width) ? (DataGridViewAutoSizeColumnMode.Fill) : (DataGridViewAutoSizeColumnMode.AllCells));
            listViewOfRecordDetails.Columns[1].AutoSizeMode = (((lstViewWdth - listViewOfRecordDetails.Columns[0].Width) > listViewOfRecordDetails.Columns[1].Width) ? (DataGridViewAutoSizeColumnMode.Fill) : (DataGridViewAutoSizeColumnMode.AllCells));

            int TotalWidthOfVisibleColumns = 0;
            foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
            {
                if ((s != null) && (s.Visible))
                {
                    TotalWidthOfVisibleColumns += s.Width;
                }
            }
            listViewOfRelatedRecordDetails.Size = new Size(Width - 2 * xPadding, listViewOfRelatedRecordDetails.Height);
            listViewOfRelatedRecordDetails.Location = new Point(xPadding, listViewOfRelatedRecordDetails.Location.Y);
            if ((TotalWidthOfVisibleColumns > listViewOfRelatedRecordDetails.Width))
            {
                TotalWidthOfVisibleColumns = 0;
                foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
                {
                    if ((s != null) && (s.Visible))
                    {
                        s.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        TotalWidthOfVisibleColumns += s.Width;
                    }
                }
            }
            if ((TotalWidthOfVisibleColumns < listViewOfRelatedRecordDetails.Width))
            {
                foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
                {
                    if ((s != null) && (s.Visible))
                    {
                        s.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    }
                }
            }

            CBoxSelectAllRelRec.Location = new Point(listViewOfRelatedRecordDetails.Location.X + 5, listViewOfRelatedRecordDetails.Location.Y + 5);

            lblNoRelRecords.Location = new Point(listViewOfRelatedRecordDetails.Location.X + ((listViewOfRelatedRecordDetails.Width - lblNoRelRecords.Width) / 2), lblNoRelRecords.Location.Y);

            nextPagePic.Location = new Point(Width - xPadding - nextPagePic.Width, nextPagePic.Location.Y);
            lblPageNum.Location = new Point(nextPagePic.Location.X - lblPageNum.Width, lblPageNum.Location.Y);
            previousPagePic.Location = new Point(lblPageNum.Location.X - previousPagePic.Width, previousPagePic.Location.Y);
            firstPagePic.Location = new Point(previousPagePic.Location.X - firstPagePic.Width, firstPagePic.Location.Y);

            PicBtnForward.Location = new Point(this.Width - PicBtnForward.Width - xPadding, PicBtnForward.Location.Y);
            PicBtnBack.Location = new Point(PicBtnForward.Location.X - PicBtnBack.Width - xPadding, PicBtnBack.Location.Y);

            SplitBtnInsertDetail.Location = new Point(Width - SplitBtnInsertDetail.Width - xPadding, SplitBtnInsertDetail.Location.Y);

            btnLookup.Location = new Point(xPadding, btnLookup.Location.Y);
            splitButton1.Location = new Point(Width - xPadding - splitButton1.Width, splitButton1.Location.Y);

            horizontalLine1.Size = new Size(Width - 2 * xPadding, horizontalLine1.Size.Height);
            horizontalLine2.Size = new Size(Width - 2 * xPadding, horizontalLine2.Size.Height);
            horizontalLine3.Size = new Size(Width - 2 * xPadding, horizontalLine3.Size.Height);
            horizontalLine4.Size = new Size(Width - 2 * xPadding, horizontalLine4.Size.Height);
            horizontalLine1.Location = new Point(xPadding, horizontalLine1.Location.Y);
            horizontalLine2.Location = new Point(xPadding, horizontalLine2.Location.Y);
            horizontalLine3.Location = new Point(xPadding, horizontalLine3.Location.Y);
            horizontalLine4.Location = new Point(xPadding, horizontalLine4.Location.Y);
            Refresh();
        }

        public void sizeChange(int pWidth, int pHeight)
        {
            this.Location = new Point(0, 0);
            this.Size = new Size(pWidth, pHeight);
        }

        public override void initializeControls(object application, object activeOne)
        {
            Application = application;
            ActiveOne = activeOne;
            InfoStatus = new InfoOptions();
            InfoStatus = InfoOptions.Free;
            thisRecord = null;

            // enable the panel for other tasks.
            this.panelOtherTask.Enabled = true;

            //search combobox
            comboBoxEntityTypeLookFor.Items.Clear();
            MainComboMapping = CrmConnector.getEntityListFromCRM(PrivilegeType.Read);
            string[] entityList = null;
            if ((MainComboMapping == null) || ((entityList = MainComboMapping[0]) == null) || (entityList.Length == 0))
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.NoEntitiesConfigured, InfoOptions.Warning);
                return;
            }

            populateCombo(ref this.comboBoxEntityTypeLookFor, entityList);
            this.comboBoxEntityTypeLookFor.SelectedItem = string.Empty;
            this.comboBoxEntityTypeLookFor.Enabled = true;
            this.FlagErrorOrWarning(string.Empty, InfoOptions.Free);

            //TextBox Search
            this.textBoxLookForText.MaxLength = 100;
            this.textBoxLookForText.Text = string.Empty;
            this.textBoxLookForText.AutoCompleteMode = AutoCompleteMode.Suggest;
            this.textBoxLookForText.AutoCompleteSource = AutoCompleteSource.CustomSource;
            TextBoxCacheSource = new AutoCompleteStringCollection();
            this.textBoxLookForText.AutoCompleteCustomSource = TextBoxCacheSource;
            toolTipForTextBox = new ToolTip();
            toolTipForTextBox.AutoPopDelay = 5000;
            toolTipForTextBox.InitialDelay = 100;
            toolTipForTextBox.ReshowDelay = 500;
            toolTipForTextBox.SetToolTip(textBoxLookForText, string.Empty);

            ClearListView();
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;

            string TableOrLabels = string.Empty;
            lnklblOtherTask.Enabled = lnklblOtherTask.Visible = true;
            if (Application is Word.Application)
            {
                if (OfficeApi.IsOutLook(ActiveOne))
                {
                    lnklblOtherTask.Enabled = lnklblOtherTask.Visible = false;
                    lblOtherTasks.Enabled = lblOtherTasks.Visible = false;
                }
                TableOrLabels = global::CRMScenarios.Resources.InsertAsTableMenu;
            }
            else if (Application is Excel.Application)
            {
                TableOrLabels = global::CRMScenarios.Resources.IncludeLabelsMenu;
            }
            else
            {
                TableOrLabels = global::CRMScenarios.Resources.UnKnownAppErrorMsg;
            }
            SplitBtnInsertDetail.ContextMenuStrip.Items[1].Text = TableOrLabels;                 
            NotBusyAnyMore();
        }

        void ContextMenuStrip_MouseCaptureChanged(object sender, EventArgs e)
        {
            SplitBtnInsertDetail.ContextMenuStrip.Visible = false;
        }

        void ContextMenuStrip1_MouseCaptureChanged(object sender, EventArgs e)
        {
            splitButton1.ContextMenuStrip.Visible = false;
        }

        void RelatedContextMenuStrip_LostFocus(object sender, EventArgs e)
        {
            SplitBtnInsertDetail.ContextMenuStrip.Visible = false;
        }

        void ContextMenuStrip_LostFocus(object sender, EventArgs e)
        {
            splitButton1.ContextMenuStrip.Visible = false;
        }

        void SplitBtnInsertDetail_InsertRec_AsTable_click(object sender, EventArgs e)
        {
                string[] detailsToBeInserted = SelectedDetailsOfRecord(true);
                OfficeApi.InsertDataToDocument(ActiveOne, this.listViewOfRecordDetails.Columns[0].HeaderText, this.listViewOfRecordDetails.Columns[1].HeaderText, detailsToBeInserted);
        }

        void SplitBtnInsertDetail_InsertRec_click(object sender, EventArgs e)
        {
            try
            {
                string[] detailsToBeInserted = SelectedDetailsOfRecord(false);
                OfficeApi.InsertDataToDocument(ActiveOne, detailsToBeInserted);
            }
            catch { }
        }

        /// <summary>
        /// Loops through the grid view and gets the detail of the selected entity.
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        private string[] SelectedDetailsOfRecord(bool table)
        {
            string[] str1InsertDetail = null;
            StringCollection strDetails = new StringCollection();
            int nodeIndex = listViewOfRecordDetails.Nodes.Count;
            for(int nIndex = 0; nIndex < nodeIndex; nIndex++)
            {
                AdvancedDataGridView.TreeGridNode item = listViewOfRecordDetails.Nodes[nIndex];
                if ( (item == null) )
                {
                    continue;
                }

                int count = item.Nodes.Count;
                    for (int i = 0; i < count; i++)
                    {
                        AdvancedDataGridView.TreeGridNode innerItem = item.Nodes[i];
                        if (innerItem == null)
                        {
                            continue;
                        }
                        if (item.Selected || innerItem.Selected)
                        {
                            if (table == true)
                            {
                                strDetails.Add((string)((innerItem.Cells[0].Value == null) ? (string.Empty) : (innerItem.Cells[0].Value)));
                            }
                            strDetails.Add((string)((innerItem.Cells[1].Value == null) ? (string.Empty) : (innerItem.Cells[1].Value)));
                        }
                    }
            }
            str1InsertDetail = new string[strDetails.Count];
            strDetails.CopyTo(str1InsertDetail, 0);
            return str1InsertDetail;
        }

        /// <summary>
        /// On change of the selected entity many controls need to be re-initialised.
        /// Done here.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmBoxSearchIn_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ChangingLookupComboProgrammatically == true)
            {
                return;
            }
            RefreshMetaDataIfNeeded();
            DisableAllControls(); // doesnt do on labels and other task panel.
            this.PicBtnBack.Enabled = GoBackAndForth.CanGoBackward();
            this.PicBtnForward.Enabled = GoBackAndForth.CanGoFroward();
            this.FlagErrorOrWarning(string.Empty, InfoOptions.Free);

            thisRecord                              = null;
            this.comboBoxEntityTypeLookFor.Enabled  = true;
            this.textBoxLookForText.Text            = string.Empty;
            textBoxLookForText.Font = new Font(textBoxLookForText.Font.FontFamily, textBoxLookForText.Font.Size, FontStyle.Regular, GraphicsUnit.Pixel);
            textBoxLookForText.Click -= new EventHandler(textBoxLookForText_Click);
            toolTipForTextBox.SetToolTip(textBoxLookForText, string.Empty);
            UpDateTxtBoxCache();
            this.textBoxLookForText.Enabled = true;
            buttonGoSearch.Enabled = true;
            this.lblNoRecordFound.Visible = false;
            ClearListView();
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;
            this.cmBoxRelated.Items.Clear();            
        }

        public override void DisableControlsWhileLookUp()
        {
            this.FlagErrorOrWarning(string.Empty, InfoOptions.Free);
            this.lblNoRecordFound.Visible = false;
            this.buttonGoSearch.Enabled = false;
            this.cmBoxRelated.Enabled = false;
            this.cBoxSelAll.Enabled = false;
            this.cBoxSelAll.CheckState = CheckState.Unchecked;
            this.SplitBtnInsertDetail.Enabled = false;
            this.splitButton1.Enabled = false;
            this.btnLookup.Enabled = false;
            ClearListView();
            this.listViewOfRecordDetails.Enabled = false;
            DisablePaging();
        }
           
        public override void getDetailsOfTheEntityAndDisplay(BusinessEntity entity, string entityType)
        {
            if (entity == null)
            {
                this.tBoxSearchFor_TextChanged(null, null);
                FlagErrorOrWarning(string.Empty, InfoOptions.Free);
                return;
            }
            ChangingLookupComboProgrammatically = true;
            this.comboBoxEntityTypeLookFor.SelectedItem = CrmConnector.NameToDisplay(entityType);
            ChangingLookupComboProgrammatically = false;

            this.textBoxLookForText.Enabled = true;
            this.buttonGoSearch.Enabled = true;

            BusinessEntity be = CrmConnector.GetAllDetailsOfThisEntity(ref entity, entityType);
            thisRecord = be;
            this.lblNoRecordFound.Visible = false;

            if(be == null)
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.NoResultFound, InfoOptions.Warning);
                return;
            }

            FillDetailsInListView(thisRecord, CrmConnector.getFormViewDescription(entityType));
            string strToBeInLookFor = ((string)CrmConnector.GetAttribute(ref thisRecord, CrmConnector.GetEntityMetaData(entityType).PrimaryField));
            this.textBoxLookForText.Text = (((strToBeInLookFor == null) || (strToBeInLookFor == string.Empty)) ? (global::CRMScenarios.Resources.UnKnown) : (strToBeInLookFor));
            textBoxLookForText.Font = new Font(textBoxLookForText.Font.FontFamily, textBoxLookForText.Font.Size, FontStyle.Underline, GraphicsUnit.Pixel);
            textBoxLookForText.Click -= new EventHandler(textBoxLookForText_Click);
            textBoxLookForText.Click += new EventHandler(textBoxLookForText_Click);
            toolTipForTextBox.SetToolTip(textBoxLookForText, global::CRMScenarios.Resources.CtrlClickToOpen);
            UpDateTxtBoxCache();

            /*
             * the following are to be done - depending on what exception we received.
             */

            this.cmBoxRelated.Items.Clear();

            // #1000
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            this.lblNoRelRecords.Visible = false;
            CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;
            this.currentRelatedBec = null;

            RelatedComboMapping = CrmConnector.GetRelatedEntityList(this.MainEntityName(), PrivilegeType.Read);
            string[] relatedEntityList = null;
            if ((RelatedComboMapping == null) || (RelatedComboMapping.Length == 0))
            {
                FlagErrorOrWarning("Error - related types", InfoOptions.Error);
            }
            else
            {
                relatedEntityList = RelatedComboMapping[0];
                if ((relatedEntityList == null) || (relatedEntityList.Length == 0))
                {
                    FlagErrorOrWarning(global::CRMScenarios.Resources.NoRelatedEntitiesConfigured, InfoOptions.Warning);
                    return;
                }
                FlagErrorOrWarning(string.Empty, InfoOptions.Free);
            }

            populateCombo(ref this.cmBoxRelated, relatedEntityList);
            this.cmBoxRelated.SelectedItem = string.Empty;
            this.cmBoxRelated.Enabled = true;
            this.cBoxSelAll.Enabled = true;
            this.cBoxSelAll.Checked = false;
            if (UsingBackForthButton == true)
            {
                return;
            }
            GoBackAndForth.NewRecordEntry(entityType, CrmConnector.GetGuid(ref entity, entityType));
            PicBtnBack.Enabled = GoBackAndForth.CanGoBackward();
            PicBtnForward.Enabled = GoBackAndForth.CanGoFroward();
        }

        private void ClearListView()
        {
            this.listViewOfRecordDetails.Nodes.Clear();
            this.listViewOfRecordDetails.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            this.listViewOfRecordDetails.Columns[1].MinimumWidth = 5;
            this.listViewOfRecordDetails.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            this.listViewOfRecordDetails.Rows.Clear();
        }

        /// <summary>
        /// Fill in the details of the selected entity in the Data Grid View. 
        /// The meta data for that is provided in the parsed form Xml.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="formXmlParsed"></param>
        public override void FillDetailsInListView(BusinessEntity entity, string[][] formXmlParsed)
        {
            ClearListView();
            this.cBoxSelAll.Checked = false;

            
            if ((entity == null) || (formXmlParsed == null) || (formXmlParsed[0] == null) || (formXmlParsed[0].Length == 0))
            {
                return;
            }

            StringCollection ExcludedAttribs = ConfigFileManager.GetExclusionList2(MainEntityName(), "attribute");

            for (int i = 1; i < formXmlParsed.Length; i++)
            {
                if ((formXmlParsed[i] == null) || 
                    (formXmlParsed[i].Length == 0) || 
                    (formXmlParsed[0].Length < (i + 1)) ||
                    (formXmlParsed[0][i] == null) ||
                    (formXmlParsed[0][i] == string.Empty))
                {
                    continue;
                }

                try
                {
                    AdvancedDataGridView.TreeGridNode Section = new AdvancedDataGridView.TreeGridNode();
                    for (int j = 0; j < (formXmlParsed[i].Length); j += 2)
                    {
                        if ((formXmlParsed[i][j] == null) || 
                            (formXmlParsed[i][j + 1] == null) ||
                            (formXmlParsed[i][j] == string.Empty) || 
                            (formXmlParsed[i][j + 1] == string.Empty) ||
                            ((ExcludedAttribs != null) && (/*(ExcludedAttribs.Contains(formXmlParsed[i][j + 1])) ||*/
                            (ExcludedAttribs.Contains(formXmlParsed[i][j])))))
                        {
                            continue;
                        }
                        AdvancedDataGridView.TreeGridNode subNode = new AdvancedDataGridView.TreeGridNode();
                        Section.Nodes.Add(subNode);
                       
                    }

                    this.listViewOfRecordDetails.Nodes.Add(Section);
                    int nodeIndex = this.listViewOfRecordDetails.Nodes.Count - 1;
                    this.listViewOfRecordDetails.Nodes[nodeIndex].Cells[0].Value = formXmlParsed[0][i];
                    int lastsubNode = 0;
                    for (int j = 0; j < (formXmlParsed[i].Length); j += 2)
                    {
                        if ((formXmlParsed[i][j] == null) || (formXmlParsed[i][j + 1] == null) ||
                            (formXmlParsed[i][j] == string.Empty) || (formXmlParsed[i][j + 1] == string.Empty) ||
                            ((ExcludedAttribs != null) && (/* (ExcludedAttribs.Contains(formXmlParsed[i][j + 1])) || */
                            (ExcludedAttribs.Contains(formXmlParsed[i][j]))
                                                                             )))
                        {
                            continue;
                        }

                        try
                        {
                            string dataBoundAttrName = CrmConnector.GetDataBoundAttribName(MainEntityName(), formXmlParsed[i][j]);
                            listViewOfRecordDetails.Nodes[nodeIndex].Nodes[lastsubNode].Cells[0].Value = formXmlParsed[i][j + 1];
                            listViewOfRecordDetails.Nodes[nodeIndex].Nodes[lastsubNode++].Cells[1].Value = (string)CrmConnector.GetAttribute(ref entity, dataBoundAttrName);
                        }
                        catch (Exception)// exp)
                        { }

                    }

                }
                catch (Exception)// exp1)
                { }
            }


            int nodeNum = listViewOfRecordDetails.Nodes.Count;
            if ((nodeNum != 0) && (listViewOfRecordDetails.Nodes[nodeNum - 1] != null))
            {
                listViewOfRecordDetails.Nodes[nodeNum - 1].Expand();
                listViewOfRecordDetails.Nodes[nodeNum - 1].Collapse();
            }
            
            this.listViewOfRecordDetails.Enabled = true;
            this.listViewOfRecordDetails.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            int minWidth = this.listViewOfRecordDetails.Width - this.listViewOfRecordDetails.Columns[0].Width;
            this.listViewOfRecordDetails.Columns[1].MinimumWidth = ((minWidth < 5) ? (5) : (minWidth));
            this.listViewOfRecordDetails.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            
            // for a bug - 746 which i dont think is needed
            //this.SplitBtnInsertDetail.Enabled = false;
        }
        
        private void setSelectValue(AdvancedDataGridView.TreeGridNode item, bool selection)
        {
            if (item == null)
            {
                return;
            }
            item.Selected = selection;
            foreach (AdvancedDataGridView.TreeGridNode innerItem in item.Nodes)
            {
                try
                {
                    innerItem.Selected = selection;
                }
                catch
                {
                    // DONT do anything... this was not added to the datagridView. 
                    // dont bother the error.
                }
            }
        }

        private void cBoxSelAll_CheckedChanged(object sender, EventArgs e)
        {
            if (selectAllChangedProgrammatically)
            {
                selectAllChangedProgrammatically = false;
                return;
            }
            attribSelectionChangedProg = true;
            foreach (AdvancedDataGridView.TreeGridNode item in this.listViewOfRecordDetails.Nodes)
            {
                setSelectValue(item, this.cBoxSelAll.Checked);
            }
            attribSelectionChangedProg = false;
        }

        private void listViewDetails_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listViewOfRecordDetails.SelectedRows.Count == 0)
            {
                SplitBtnInsertDetail.Enabled = false;
                return;
            }

            SplitBtnInsertDetail.Enabled = true;

            if (attribSelectionChangedProg == true)
            {
                return;
            }

            selectAllChangedProgrammatically = true;
            if (this.listViewOfRecordDetails.Rows.Count == this.listViewOfRecordDetails.SelectedRows.Count)
            {
                cBoxSelAll.Checked = true;
                cBoxSelAll.CheckState = CheckState.Checked;
            }
            else
            {
                cBoxSelAll.Checked = false;
                cBoxSelAll.CheckState = CheckState.Unchecked;
            }
            selectAllChangedProgrammatically = false;
        }

        private void lblCBoxSelectAll_Click(object sender, EventArgs e)
        {
            if (cBoxSelAll.Enabled == true)
            {
                cBoxSelAll.Checked = !(cBoxSelAll.Checked);
            }
        }

        /// <summary>
        /// Report error/warning on the botton of the pane.
        /// </summary>
        private void GiveWarningOrError()
        {

        }

        private void lnklblWarning_Click(object sender, EventArgs e)
        {
            GiveWarningOrError();
        }

        private void picWarning_Click(object sender, EventArgs e)
        {
            GiveWarningOrError();
        }

        private void lnkLblTips_Click(object sender, EventArgs e)
        {
            GiveHelpOrTips("how_IBF_insert.htm");
        }

        private void picHelp_Click(object sender, EventArgs e)
        {
            GiveHelpOrTips("how_IBF_insert.htm");
        }

        private void lnklblOtherTask_Click(object sender, EventArgs e)
        {
            ((ActionsPane)this.Parent).changeScenario(2, MainEntityName(),
                textBoxLookForText.Text, ref thisRecord, RefreshOption.FromLink);// hard coded '2' for scenario attach doc.
        }

        /// <summary>
        /// On click of the browse button. Get the details and display on the top grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLookup_Click(object sender, EventArgs e)
        {
            MakeItLookBusy(global::CRMScenarios.Resources.FetchingAllDetails);
            getDetailsOfTheEntityAndDisplay(selectedRelatedRecord, this.RelatedEntityName());
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;
            this.listViewOfRelatedRecordDetails.Enabled = false;
            this.cBoxSelAll.Checked = false;
            NotBusyAnyMore();
        }

        private void lblSearchIn_Click(object sender, EventArgs e)
        {

        }

        private void listViewRelated_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (this.listViewOfRelatedRecordDetails.SelectedRows.Count == 0)
            {
                this.btnLookup.Enabled = false;
                this.splitButton1.Enabled = false;
                return;
            }

            this.splitButton1.Enabled = true;

            if (RelatedGridSelectionChangeProgramattically == true)
            {
                return;
            }

            CBoxSelectAllRelRecChangedProgrammatically = true;
            CBoxSelectAllRelRec.Checked = (listViewOfRelatedRecordDetails.SelectedRows.Count == listViewOfRelatedRecordDetails.Rows.Count);
            CBoxSelectAllRelRecChangedProgrammatically = false;

            if (this.listViewOfRelatedRecordDetails.SelectedRows.Count == 1)
            {
                if ((currentRelatedBec != null) && (currentRelatedBec.BusinessEntities.Length > listViewOfRelatedRecordDetails.SelectedRows[0].Index))
                {
                    selectedRelatedRecord = currentRelatedBec.BusinessEntities[listViewOfRelatedRecordDetails.SelectedRows[0].Index];
                    btnLookup.Enabled = !CrmConnector.IsNonMainEntity(RelatedEntityName());

                    return;
                }
            }
            
            this.btnLookup.Enabled = false;
        }

        private void InsertRelatedRecords()
        {
            string[][] dataToBeInserted = new string[this.listViewOfRelatedRecordDetails.SelectedRows.Count + 1][];

            int numberOfCols = this.listViewOfRelatedRecordDetails.Columns.Count;
            //dataToBeInserted[0] = new string[numberOfCols];

            StringCollection columnsAlreadyPresent = new StringCollection();
            foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
            {
                if (s.Visible == true)
                {
                    columnsAlreadyPresent.Add(s.Name);
                }
            }
            dataToBeInserted[0] = new string[columnsAlreadyPresent.Count];
            columnsAlreadyPresent.CopyTo(dataToBeInserted[0], 0);
            for (int i = 0; i < dataToBeInserted[0].Length; i++)
            {
                dataToBeInserted[0][i] = this.listViewOfRelatedRecordDetails.Columns[dataToBeInserted[0][i]].HeaderText; // .Text;
            }

            int row = 0; 
            for(row = 0; row < this.listViewOfRelatedRecordDetails.SelectedRows.Count; row++)
            {
                dataToBeInserted[row + 1] = new string[columnsAlreadyPresent.Count];
                for (int col = 0; col < columnsAlreadyPresent.Count ; col++)
                {
                    try
                    {
                        dataToBeInserted[row+1][col] = 
                            (string)this.listViewOfRelatedRecordDetails.SelectedRows[row].Cells[columnsAlreadyPresent[col]].Value;
                    }
                    catch { }
                }
            }

            
            OfficeApi.InsertAnyDataToDocAsTable(ActiveOne, dataToBeInserted);
        }

        public void InsertRelatedRecordsWithAdditionalColumns(string[] selectedAttributes)
        {
            if ((selectedAttributes == null) || (selectedAttributes.Length == 0))
            {
                return;
            }
            string[][] dataToBeInserted = new string[selectedIndicesOfRelatedRecords.Length + 1][];
            int numberOfCols = selectedAttributes.Length;
            dataToBeInserted[0] = selectedAttributes;
            string relEntName = this.RelatedEntityName();
            string[] realAttribueNames = CrmConnector.GetRealNameOfDisplayAttribs(relEntName, selectedAttributes);
            string[] DataBoundAttribNames = CrmConnector.GetDataBoundAttribNames(relEntName, realAttribueNames);
            MakeItLookBusy(global::CRMScenarios.Resources.InsertingData);
            for (int row = 0; row < selectedIndicesOfRelatedRecords.Length; row++)
            {
                BusinessEntity entity = currentRelatedBec.BusinessEntities[selectedIndicesOfRelatedRecords[row]];
                BusinessEntity entityWithRequiredFields = CrmConnector.GetSpecifiedDetailsOfThisEnity(entity, this.RelatedEntityName(), realAttribueNames);
                if (entityWithRequiredFields == null)
                {
                    FlagErrorOrWarning(global::CRMScenarios.Resources.ErrorInSearching, InfoOptions.Error);
                    return;
                }

                dataToBeInserted[row + 1] = new string[numberOfCols];// do note: first row was the headers...!!
                for (int col = 0; col < DataBoundAttribNames.Length; col++)
                {
                    object obj = CrmConnector.GetAttribute(ref entityWithRequiredFields, DataBoundAttribNames[col]);
                    dataToBeInserted[row + 1][col] = ((obj != null) ?  // do note: first row was the headers...!!
                                                  ((obj.GetType() == typeof(System.String)) ?
                                                   ((string)obj) :
                                                    (string.Empty)) :
                                                    (string.Empty));

                }
            }
            OfficeApi.InsertAnyDataToDocAsTable(ActiveOne, dataToBeInserted);
            NotBusyAnyMore();
            selectedIndicesOfRelatedRecords = null;
        }

        private void InsertFlds_Load(object sender, EventArgs e)
        {
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }

        private void twoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InsertRelatedRecords();
        }

        private void threeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            selectedIndicesOfRelatedRecords = new int[this.listViewOfRelatedRecordDetails.SelectedRows.Count];
            for (int i = 0; i < this.listViewOfRelatedRecordDetails.SelectedRows.Count; i++)
            {
                selectedIndicesOfRelatedRecords[i] = this.listViewOfRelatedRecordDetails.SelectedRows[i].Index;
            }
            StringCollection columnsAlreadyPresent = new StringCollection();
            foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
            {
                if (s.Visible == true)
                {
                    columnsAlreadyPresent.Add(s.Name);
                }
            }
            PickListForm pickList = new PickListForm();
            pickList.InitPickListForm(this.RelatedEntityName(), this, columnsAlreadyPresent);
            pickList.ShowDialog();
            OfficeApi.ActivateWindow(ActiveOne);
        }

        private void SplitBtnInsertDetail_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Remove the hyperlink on change of the text
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxLookForText_TextChanged(object sender, EventArgs e)
        {

        }

        void CBoxSelectAllRelRec_CheckedChanged(object sender, EventArgs e)
        {
            if (CBoxSelectAllRelRecChangedProgrammatically)
            {
                return;
            }
            RelatedGridSelectionChangeProgramattically = true;
            foreach (DataGridViewRow row in listViewOfRelatedRecordDetails.Rows)
            {
                row.Selected = CBoxSelectAllRelRec.Checked;
            }
            RelatedGridSelectionChangeProgramattically = false;
        }

        private void UndoUnderLineTheLabel(object sender, EventArgs e)
        {
            ((Label)sender).Font = new Font(((Label)sender).Font.FontFamily, ((Label)sender).Font.Size, FontStyle.Regular, GraphicsUnit.Pixel);
            this.Cursor = Cursors.Default;
        }

        private void UnderLineTheLabel(object sender, EventArgs e)
        {
            if (InfoStatus == InfoOptions.Busy)
            {
                return;
            }

            if (((Label)sender).Name == lnklblWarning.Name)
            {
                if (InfoStatus != InfoOptions.Error)
                {
                    return;
                }
            }
            ((Label)sender).Font = new Font(((Label)sender).Font.FontFamily, ((Label)sender).Font.Size, FontStyle.Underline, GraphicsUnit.Pixel);
            this.Cursor = Cursors.Hand;
        }

        void panelOtherTask_MouseDown(object sender, MouseEventArgs e)
        {
            panelOtherTask.Focus();
        }

        void textBoxLookForText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                buttonGoSearch_Click(null, null);
            }
        }

        private void dataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs location)
        {
            mouseLocation = location;
        }

        private void DGView_Click_Two(object sender, EventArgs e)
        {
            BusinessEntity rightClickedRecord = currentRelatedBec.BusinessEntities[mouseLocation.RowIndex];
            MakeItLookBusy(global::CRMScenarios.Resources.OpeningWebPage);
            string Url = CrmConnector.UrlForThisEntity(this.RelatedEntityName(), ref rightClickedRecord);
            NotBusyAnyMore();
            if ((Url == null) || (Url == string.Empty))
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.BrowserPageNotSupported + cmBoxRelated.Text, InfoOptions.Warning);
                return;
            }
            OpenPage(CrmConnector.UrlForThisEntity(this.RelatedEntityName(), ref rightClickedRecord));
        }

        private void DGView_Click_One(object sender, EventArgs e)
        {
            BusinessEntity rightClickedRecord = currentRelatedBec.BusinessEntities[mouseLocation.RowIndex];
            MakeItLookBusy(global::CRMScenarios.Resources.FetchingAllDetails);
            getDetailsOfTheEntityAndDisplay(rightClickedRecord, this.RelatedEntityName());
            NotBusyAnyMore();
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            this.listViewOfRelatedRecordDetails.Enabled = false;
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            if (CBoxSelectAllRelRec != null)
            {
                CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;
            }
        }

        private void tBoxSearchFor_TextChanged(object sender, EventArgs e)
        {
            textBoxLookForText.Click -= new EventHandler(textBoxLookForText_Click);
            toolTipForTextBox.SetToolTip(textBoxLookForText, string.Empty);
            textBoxLookForText.Font = new Font(textBoxLookForText.Font.FontFamily, textBoxLookForText.Font.Size, FontStyle.Regular, GraphicsUnit.Pixel);
        }

        private void textBoxLookForText_Click(object sender, EventArgs e)
        {
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                MakeItLookBusy(global::CRMScenarios.Resources.OpeningWebPage);
                string Url = CrmConnector.UrlForThisEntity(this.MainEntityName(), ref thisRecord);
                NotBusyAnyMore();
                if ((Url == null) || (Url == string.Empty))
                {
                    FlagErrorOrWarning(global::CRMScenarios.Resources.BrowserPageNotSupported + comboBoxEntityTypeLookFor.Text, InfoOptions.Warning);
                    return;
                }
                OpenPage(Url);
            }
        }

        /// <summary>
        /// On change of the selection in related combobox, refresh the controls below that.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmBoxRelated_SelectedIndexChanged(object sender, EventArgs e)
        {
            MakeItLookBusy(global::CRMScenarios.Resources.RetrievingRelRecords);
            PageChange(pageInfo.FirstPage());
            NotBusyAnyMore();
            BusinessEntity be = null;
            if ((currentRelatedBec != null) && (currentRelatedBec.BusinessEntities.Length > 0))
            {
                be = currentRelatedBec.BusinessEntities[0];
            }
            ActivateAttachAsNeeded(RelatedEntityName(), ref be);
        }

        /// <summary>
        /// Add context menu for each of the cells 
        /// </summary>
        protected override void AddContextMenu()
        {
            ToolStripMenuItem toolStripItem1 = new ToolStripMenuItem();
            toolStripItem1.Text = btnLookup.Text;
            toolStripItem1.Click -= new EventHandler(DGView_Click_One);
            toolStripItem1.Click += new EventHandler(DGView_Click_One);
            ToolStripMenuItem toolStripItem2 = new ToolStripMenuItem();
            toolStripItem2.Text = global::CRMScenarios.Resources.ContextMenuViewInCRM;
            toolStripItem2.Click -= new EventHandler(DGView_Click_Two);
            toolStripItem2.Click += new EventHandler(DGView_Click_Two);
            ContextMenuStrip strip = new ContextMenuStrip();
            foreach (DataGridViewRow row in listViewOfRelatedRecordDetails.Rows)
            {
                row.ContextMenuStrip = strip;
                if (!CrmConnector.IsNonMainEntity(RelatedEntityName()))
                {
                    row.ContextMenuStrip.Items.Add(toolStripItem1);
                }
                row.ContextMenuStrip.Items.Add(toolStripItem2);
                foreach (DataGridViewCell cell in row.Cells)
                {
                    cell.ErrorText = string.Empty;
                    cell.ToolTipText = global::CRMScenarios.Resources.ToolTipRelatedRecordView;
                }
            }
        }

        private void firstPagePic_Click(object sender, EventArgs e)
        {
            PageChange(pageInfo.FirstPage());
        }

        private void previousPagePic_Click(object sender, EventArgs e)
        {
            PageChange(pageInfo.PrevPage());
            //EnablePaging();
        }

        private void nextPagePic_Click(object sender, EventArgs e)
        {
            PageChange(pageInfo.NextPage());
            //EnablePaging();
        }

        private void PicBtnBack_Click(object sender, EventArgs e)
        {
            GoBackAndForth.MoveBackvard();
            string eType = GoBackAndForth.RecordType();
            Guid guid = GoBackAndForth.RecordId();
            MoveBackAndForth(guid, eType);
        }

        private void PicBtnForward_Click(object sender, EventArgs e)
        {
            GoBackAndForth.MoveForward();
            string eType = GoBackAndForth.RecordType();
            Guid guid = GoBackAndForth.RecordId();
            MoveBackAndForth(guid, eType);
        }

        private void listViewOfRelatedRecordDetails_DoubleClick(object sender, EventArgs e)
        {
            if (((DataGridViewCellEventArgs)e).RowIndex < 0)
            {
                return;
            }

            if (CrmConnector.IsNonMainEntity(RelatedEntityName()))
            {
                return;
            }

            if (this.listViewOfRelatedRecordDetails.SelectedRows.Count == 1)
            {
                BusinessEntity entity = currentRelatedBec.BusinessEntities[this.listViewOfRelatedRecordDetails.SelectedRows[0].Index];
                MakeItLookBusy(global::CRMScenarios.Resources.OpeningWebPage);
                string Url = CrmConnector.UrlForThisEntity(this.RelatedEntityName(), ref entity);
                NotBusyAnyMore();
                if ((Url == null) || (Url == string.Empty))
                {
                    FlagErrorOrWarning(global::CRMScenarios.Resources.BrowserPageNotSupported + this.RelatedEntityName(), InfoOptions.Warning);
                    return;
                }
                OpenPage(Url);
            }
        }

        /// <summary>
        /// On click of the search button, do a minimal search and take action depending on the result set.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArg"></param>
        private void buttonGoSearch_Click(object sender, EventArgs eventArg)
        {
            if (comboBoxEntityTypeLookFor.Text.Length == 0)
            {
                this.buttonGoSearch.Enabled = false;
                return;
            }

            BusinessEntityCollection becRetrievedEntities = null;
            string searchPattern = textBoxLookForText.Text;
            string searchIn = MainEntityName();
            int countOfEntities = -1;
            DisableControlsWhileLookUp();

            this.listViewOfRelatedRecordDetails.Enabled = false;
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            if (CBoxSelectAllRelRec != null)
            {
                CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;
            }

            if ((searchPattern == null) || (searchPattern == string.Empty))
            {
                CreateAndShowANewLookUpDlg(searchIn, searchPattern);
                this.buttonGoSearch.Enabled = true;
                return;
            }

            MakeItLookBusy(global::CRMScenarios.Resources.PleaseWait);
            becRetrievedEntities = CrmConnector.DoRealSearchBringMinimal(searchIn, searchPattern, null);
            NotBusyAnyMore();

            if (becRetrievedEntities != null)
            {
                countOfEntities = becRetrievedEntities.BusinessEntities.Length;
            }

            switch (countOfEntities)
            {
                case -1:
                    this.FlagErrorOrWarning(global::CRMScenarios.Resources.ErrorInSearching, InfoOptions.Error);
                    break;

                case 0:
                    this.lblNoRecordFound.Visible = true;
                    this.lblNoRecordFound.BringToFront();
                    CreateAndShowANewLookUpDlg(searchIn, searchPattern);
                    break;

                case 1:
                    MakeItLookBusy(global::CRMScenarios.Resources.SingleRecordFound);
                    getDetailsOfTheEntityAndDisplay(becRetrievedEntities.BusinessEntities[0], searchIn);
                    NotBusyAnyMore();
                    break;

                default:
                    CreateAndShowANewLookUpDlg(searchIn, searchPattern);
                    break;
            }
            this.buttonGoSearch.Enabled = true;
        }

        void RelatedGridDataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }
    }
}